package android.slc.module.project.ui.crawler

import android.slc.utils.SlcPathUtils
import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.CharsetUtil
import cn.hutool.core.util.StrUtil
import cn.hutool.log.Log
import com.teamdev.jxbrowser.dom.Element
import com.teamdev.jxbrowser.dom.Node
import com.teamdev.jxbrowser.frame.Frame
import com.teamdev.jxbrowser.navigation.event.FrameDocumentLoadFinished
import java.time.LocalDate
import kotlin.jvm.optionals.getOrNull

/**
 * @author slc
 * @date 2025/5/6
 **/
class ChineseAlmanacVmSub : CrawlerVmSub() {

    private var localDate = LocalDate.of(2025, 1, 1)

    override fun getUrl(): String {
        return StrUtil.format(
            "https://www.d5168.com/huangli/{}-{}-{}",
            localDate.year,
            localDate.monthValue,
            localDate.dayOfMonth
        )
    }

    override fun onFrameDocumentLoadFinished(event: FrameDocumentLoadFinished) {
        val frame: Frame = event.frame()
        val document = frame.document().getOrNull()
        val element = document?.documentElement()?.getOrNull()
        element?.let { itElement ->
            val colLeftElement = itElement.findElementByClassName("col_left").getOrNull() ?: return@let
            val nodeList: List<Node> = colLeftElement.children()
            val overall: Element = nodeList[1] as Element
            val time: Element = nodeList[3] as Element
            val saveFilePath = SlcPathUtils.createAppFileFile(
                StrUtil.format(
                    "ChineseAlmanac{}-{}.txt",
                    localDate.year,
                    localDate.monthValue
                )
            )
            FileUtil.appendString(overall.textContent(), saveFilePath, CharsetUtil.UTF_8)
            FileUtil.appendString(time.textContent(), saveFilePath, CharsetUtil.UTF_8)
            localDate = localDate.plusDays(1)
            refreshEvent.valuePlus = true
        }
    }
}